﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Threading;
using work_log.worklogservices;
using work_log.FileService;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;

namespace work_log {
    public partial class frmAddLog : DevExpress.XtraEditors.XtraForm {
        #region 全局变量
        /// <summary>
        /// UI线程同步上下文
        /// </summary>
        private SynchronizationContext LogContext = null;
        /// <summary>
        /// 需要执行的方法
        /// </summary>
        private string setName = "";
        /// <summary>
        /// 全局线程变量
        /// </summary>
        private Thread LogThread = null;
        /// <summary>
        /// 私有文件集合
        /// </summary>
        private List<FileLogs> listFile = null;
        /// <summary>
        /// 日志为添加时候生成新的id
        /// </summary>
        private Guid newWId = Guid.Empty;
        /// <summary>
        /// 工作日志返回记录
        /// </summary>
        private ResultInfoOfWorkLogs result = null;
        /// <summary>
        /// 工作实体(填充数据)
        /// </summary>
        private WorkLogs entity = null;
        /// <summary>
        /// 文件结果集
        /// </summary>
        private ResultInfoOfFileLogs resultFile = null;
        #endregion
        public frmAddLog() {
            InitializeComponent();
            LogContext = SynchronizationContext.Current;
        }

        private void tableLayoutPanel2_Paint(object sender, PaintEventArgs e) {

        }

        private void frmAddLog_Load(object sender, EventArgs e) {
            this.gridView1.CustomDrawRowIndicator += gridView1_CustomDrawRowIndicator;
            this.gridView1.PopupMenuShowing += gridView1_PopupMenuShowing;

            //取消自适应大小时闪烁
            flowLayoutPanel1.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(tableLayoutPanel1, true, null);
            flowLayoutPanel2.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(tableLayoutPanel2, true, null);

            this.gridView1.IndicatorWidth = 40;

            if (WorkLogInfo.wId != Guid.Empty)
                this.lblTitle.Text = this.Text = "日志修改";
            else
                this.lblTitle.Text = this.Text = "日志添加";
        }


        #region GridView Opertion
        void gridView1_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e) {
            if (this.gridView1.RowCount == 0) {
                删除ToolStripMenuItem.Visible = false;
            } else {
                删除ToolStripMenuItem.Visible = true;
            }
        }

        void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e) {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0) {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        #endregion

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) {
            if (this.gridView1.RowCount > 0) {
                this.gridView1.DeleteRow(this.gridView1.FocusedRowHandle);
            }
        }

        private void frmAddLog_Shown(object sender, EventArgs e) {
            if (WorkLogInfo.wId != Guid.Empty) {
                pgWork.Description = "正在加载数据 ...";
                pgWork.Visible = true;
                this.btnSave.Enabled = false;
                this.gridControl1.ContextMenuStrip = null;
                LogThread = new Thread(new ThreadStart(this.Init));
                LogThread.Start();
            } else {
                newWId = Guid.NewGuid();
            }
        }

        //上传
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            try {
                string[] filePath = null;
                listFile = new List<FileLogs>();
                using (OpenFileDialog dialog = new OpenFileDialog()) {
                    dialog.Multiselect = true;
                    dialog.Filter = "Word文档(*.doc)|*.doc|Word文档(*.docx)|*.docx|Excel文档(*.xls)|*.xls|Excel文档(*.xlsx)|*.xlsx|文本文档(*.txt)|*.txt|RTF文档(*.rtf)|*.rtf|GIF图片(*.gif)|*.gif|JPG图片(*.jpg)|*.jpg|BMP图片(*.bmp)|*.bmp";
                    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                        filePath = new string[dialog.FileNames.Length];
                        filePath = dialog.FileNames;

                        Guid insertWId = WorkLogInfo.wId == Guid.Empty ? newWId : WorkLogInfo.wId;
                        StringBuilder removeName = new StringBuilder();
                        for (int i = 0; i < filePath.Length; i++) {
                            FileLogs entityFile = new FileLogs();
                            FileStream fs = new FileStream(filePath[i], FileMode.Open);
                            if (fs.Length > 20971520) {
                                removeName.Append("文件：" + Path.GetFileNameWithoutExtension(filePath[i]) + "超过限制大小！\r\n");
                                continue;
                            }
                            // byte[] byData = br.ReadBytes((int)fs.Length);
                            byte[] byData = new byte[fs.Length];
                            fs.Read(byData, 0, byData.Length);
                            entityFile.FSize = byData.Length.ToString();
                            fs.Close();

                            entityFile.FId = Guid.NewGuid();
                            entityFile.FAuthor = UserInfo.uName;
                            entityFile.FName = Path.GetFileNameWithoutExtension(filePath[i]);

                            entityFile.FExtiend = Path.GetExtension(filePath[i]);
                            entityFile.FFile = byData;
                            entityFile.FStatus = "0";
                            entityFile.FUploadTime = DateTime.Now;
                            entityFile.wId = insertWId;
                            listFile.Add(entityFile);
                        }
                        if (removeName.ToString() != string.Empty)
                            XtraMessageBox.Show(removeName.ToString());

                        LogThread = new Thread(new ThreadStart(this.InitFileTable));
                        LogThread.Start();
                    }
                }
            } catch (Exception ex1) {
                MessageBox.Show(ex1.Message);
            }
        }

        private void btnSave_Click(object sender, EventArgs e) {
            if (txtTitle.Text.Trim() == "") {
                lblMSG.Text = "标题不准为空！";
                lblMSG.ForeColor = Color.Red;
                txtTitle.Select();
                return;
            } else if (txtContent.Text == "") {
                lblMSG.Text = "内容不准为空！";
                lblMSG.ForeColor = Color.Red;
                txtContent.Select();
                return;
            }
            lblMSG.Text = "";
            this.pgWork.Description = "正在传输数据中，请稍等 ...";
            this.pgWork.Visible = true;
            this.btnSave.Enabled = false;

            #region 填充数据
            if (WorkLogInfo.wId == Guid.Empty) {
                entity = new WorkLogs();
                entity.wId = newWId;
                entity.wTitle = txtTitle.Text.Trim();
                entity.wContent = txtContent.Text;
                entity.wRtfContent = GZipClass.Base64Compress(txtContent.Rtf);
                entity.wCreateDate = entity.wUpdateDate = DateTime.Now;
                entity.wStatus = "0";
                entity.User_uid = UserInfo.uid;
            } else {
                entity = new WorkLogs();
                entity.wId = WorkLogInfo.wId;
                entity.wTitle = txtTitle.Text.Trim();
                entity.wContent = txtContent.Text;
                entity.wRtfContent = GZipClass.Base64Compress(txtContent.Rtf);
                entity.wUpdateDate = DateTime.Now;
                entity.wStatus = "1";
            }
            #endregion

            LogThread = new Thread(new ThreadStart(this.Commit));
            LogThread.Start();
        }

        #region Custom Opertion
        private void Commit() {
            try {
                if (WorkLogInfo.wId == Guid.Empty) {
                    //TDDO:  添加方法
                    result = new workLogServicesSoapClient().Add(entity);
                } else {
                    //TDDO:  修改方法
                    result = new workLogServicesSoapClient().Edit(entity);
                }
                if (listFile != null) {
                    resultFile = new FileLogsServicesSoapClient().AddList(listFile.ToArray());
                }
                setName = "InitData";
                LogContext.Post(LogSafeOpertion, "");
            } catch (Exception ex) {
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void InitFileTable() {
            if (listFile != null && listFile.Count > 0) {
                setName = "LoadFileTable";
                LogContext.Post(LogSafeOpertion, listFile);
            }
        }
        #endregion

        #region Init
        private void Init() {
            try {
                worklogservices.ResultInfoOfWorkLogs resultLog = new worklogservices.workLogServicesSoapClient().FindById(WorkLogInfo.wId);
                resultFile = new FileService.FileLogsServicesSoapClient().FindByWId(WorkLogInfo.wId);
                if (resultLog.Result) {
                    setName = "LoadData";
                    LogContext.Post(LogSafeOpertion, resultLog.Data);
                }
            } catch (Exception ex) {
                setName = "Loading";
                LogContext.Post(LogSafeOpertion, "");
                XtraMessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region ThreadSafe Opertion
        private void LogSafeOpertion(object sender) {
            if (sender != null) {
                if (setName == "LoadData") {
                    #region 加载数据
                    WorkLogs entity = (WorkLogs)sender;
                    txtTitle.Text = entity.wTitle;
                    if (entity.wRtfContent != string.Empty) {
                        txtContent.Rtf = GZipClass.Base64Decompress(entity.wRtfContent);
                    } else {
                        txtContent.Text = entity.wContent;
                    }

                    if (resultFile.Result) {
                        MemoryStream ms = new MemoryStream((byte[])resultFile.DataFormat);
                        IFormatter formatData = new BinaryFormatter();
                        gridControl1.DataSource = (DataTable)formatData.Deserialize(ms);
                    } else {
                        XtraMessageBox.Show(result.MSG);
                    }
                    pgWork.Visible = false;
                    this.btnSave.Enabled = true;
                    #endregion
                } else if (setName == "Loading") {
                    pgWork.Visible = false;
                } else if (setName == "LoadFileTable") {
                    this.gridControl1.DataSource = (List<FileLogs>)sender;
                } else if (setName == "InitData") {
                    if (result.Result) {
                        if (resultFile != null) {
                            if (resultFile.Result) {
                                pgWork.Visible = false;
                                this.btnSave.Enabled = true;
                                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                                this.Close();
                                return;
                            } else {
                                XtraMessageBox.Show("上传文件：" + resultFile.MSG + "，稍后请重新上传");
                            }
                        }
                        pgWork.Visible = false;
                        this.btnSave.Enabled = true;
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    } else {
                        XtraMessageBox.Show(result.MSG);
                    }
                }
            }
        }
        #endregion
    }
}